package ynu.edu.elmspringboot.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import ynu.edu.elmspringboot.utils.JwtUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 处理OPTIONS请求
        if (req.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 获取请求url
        String url = req.getRequestURL().toString();
        // 排除根路径 "/" 的请求
        if (url.equals("http://localhost:8081/")) {
            return true;
        }
        // 如果是登录请求，直接放行
        if (url.contains("login") || url.contains("register") ||
                url.contains("getUserInfo") || url.contains("getUserById")) {
            return true;
        }

        if (url.contains("/doc.html") || url.contains("/swagger-resources") || url.contains("/v2/api-docs")|| url.contains("/webjars/")|| url.contains("/favicon.ico")) {
            return true;
        }

        // 获取请求头中的 Authorization 字段
        String authHeader = req.getHeader("Authorization");
        // 判断 Authorization 请求头是否存在，且格式是否正确
        if (!StringUtils.hasLength(authHeader) || !authHeader.startsWith("Bearer ")) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"error\":\"Unauthorized: Please login\"}");
            return false;
        }

        String jwt = authHeader.substring(7);
        // 解析token
        try {
            log.info("jwt校验:{}", jwt);
            JwtUtil.parseJWT(jwt);
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"error\":\"Invalid token\"}");
            return false;
        }
        return true;
    }
}